package com.crm.system.service.impl.couponManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.couponManager.Coupon;
import com.crm.model.entity.couponManager.CouponIssued;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.couponManager.CouponIssuedQO;
import com.crm.model.qo.orderManager.CustomerProductOrderQO;
import com.crm.model.vo.couponManager.CouponIssuedVO;
import com.crm.model.vo.orderManager.CustomerProductOrderVO;
import com.crm.service.couponManager.CouponDbService;
import com.crm.service.couponManager.CouponIssuedDbService;
import com.crm.system.service.couponManager.CouponIssuedService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author renshaorong
 * @Date 2021/11/9
 */
@Service
public class CouponIssuedServiceImpl implements CouponIssuedService {

    @Autowired
    private CouponIssuedDbService couponIssuedDbService;

    @Autowired
    private CouponDbService couponDbService;

    @Override
    public DhPageInfo<CouponIssuedVO> selectCouponIssuedPageList(CouponIssued couponIssued, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if(!StringUtils.isBlank(sortName)&&!StringUtils.isBlank(sortOrder)){
            switch(sortName){
                case "createTm":
                {
                    order.append("ci.create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<CouponIssuedVO> productActivityVOList = couponIssuedDbService.selectCouponIssuedPageList(couponIssued,order.toString());
        PageInfo<CouponIssuedVO> pageInfo = new PageInfo<CouponIssuedVO>(productActivityVOList);
        return new DhPageInfo<CouponIssuedVO>(pageInfo, productActivityVOList);
    }

    /**
     * 派发优惠券
     * @param couponIssuedQO
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public JSONObject addCouponToCustomer(CouponIssuedQO couponIssuedQO) {
        JSONObject jsonObject = new JSONObject();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<Map<String,String>> productOrderList = couponIssuedQO.getProductOrderIdList();//订单集合
        List<String> couponIdList = couponIssuedQO.getCouponIdList();//优惠券集合
        List<CouponIssued> couponIssuedList = new ArrayList<>();

        //验证优惠券剩余数量
        List<Coupon> couponList = couponDbService.selectCouponsByIdList(couponIdList);
        //客户数量
        int size = productOrderList.size();
        for (Coupon coupon : couponList) {
            //剩余优惠券数量
            int remaining = coupon.getCouponCount() - coupon.getCouponUseCount();
            if(remaining < size){
                jsonObject.put("result","\""+coupon.getCouponName()+"\"剩余数量为"+remaining+"，不足"+size+"张，请重新选择客户");
                return jsonObject;
            }
            //整理要存入对应关系表的数据
            for (Map<String,String> productOrder : productOrderList) {
                CouponIssued couponIssued = new CouponIssued();
                couponIssued.setReceiveCouponId(CommonUtils.getGUID());
                couponIssued.setChsCustomerCouponId(coupon.getChsCustomerCouponId());
                couponIssued.setCreatePeopleId(userAccount.getAccountId());
                couponIssued.setCreateTm(new Date());
                couponIssued.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                couponIssued.setUsed((short) 0);
                couponIssued.setProductOrderId(productOrder.get("productOrderId"));
                couponIssued.setCustomerId(productOrder.get("customerId"));
                couponIssuedList.add(couponIssued);
            }

            //修改优惠券已使用数量
            coupon.setCouponUseCount(coupon.getCouponUseCount() + size);
            couponDbService.updateCoupon(coupon);
        }
        boolean insertCouponIssued = couponIssuedDbService.insertBatch(couponIssuedList);
        if(!insertCouponIssued){//插入失败返回false
            jsonObject.put("result","服务器错误");
            return jsonObject;
        }
        jsonObject.put("result","000000");
        return jsonObject;
    }

    /**
     * 订单列表
     * @Author renshaorong
     * @Date 2021/11/11
     * @param pageIndex -页码
     * @param pageSize -分页大小
     * @param customerProductOrderQO -查询条件
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     */
    @Override
    public DhPageInfo<CustomerProductOrderVO> selectCustomerProductOrder(Integer pageIndex, Integer pageSize,
                                                                               CustomerProductOrderQO customerProductOrderQO,
                                                                               String sortName, String sortOrder) {
        List<CustomerProductOrderVO> customerProductOrderList = new ArrayList<CustomerProductOrderVO>();
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序字符串拼接
//        String order = getOrder(sortName, sortOrder);
        String order = null;
        customerProductOrderList = couponIssuedDbService.selectCustomerProductOrder(customerProductOrderQO, order);
        PageInfo<CustomerProductOrderVO> pageInfo = new PageInfo<CustomerProductOrderVO>(customerProductOrderList);
        return new DhPageInfo<CustomerProductOrderVO>(pageInfo, customerProductOrderList);
    }


    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/4/29 16:38
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String sortName, String sortOrder) {
        String order = "";
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch(sortName){
                case "customerName":
                { //订单编号
                    order = getOrder(order, sortOrder, "customer_name");
                }
                break;
                case "createTm":
                { //订单状态
                    order = getOrder(order, sortOrder, "create_tm");
                }
                break;
                default:
                    break;
            }
        }
        if (!order.contains("create_tm")) {
            order = getOrder(order, "DESC", "create_tm");
        }
        return order;
    }

    /**
     * 排序字符串拼接
     * @Author pym
     * @Date  2021/4/29 16:41
     * @param order -排序字符串
     * @param sortName -排序列名字
     * @param sortOrder -排序规则(asc/desc)
     * @return {@link {java.lang.String}}
     */
    private String getOrder(String order, String sortOrder, String sortName) {
        if (StringUtils.isBlank(order)) {
            order += sortName +" "+ sortOrder;
        } else {
            order += ","+sortName +" " + sortOrder;
        }
        return order;
    }

}
